package com.lu.model.domain;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lu.model.dto.UserRoleResourcesDTO;
import com.lu.model.entity.SysRole;
import com.lu.model.entity.SysUser;
import lombok.Data;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 用户信息
 * @Author: zhanglu
 * @Date: 2022/7/26 17:06
 */
@Data
public class LoginUser implements UserDetails {

  private static final long serialVersionUID = 1702923242319850756L;

  private boolean enabled;
  private boolean accountNonExpired;
  private boolean credentialsNonExpired;
  private boolean accountNonLocked;
  private SysUser user;
  private List<SimpleGrantedAuthority> authorities;

  public LoginUser(){}

  public LoginUser(SysUser user, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, List<UserRoleResourcesDTO> resources) {
    if (user != null
        && StrUtil.isNotBlank(user.getUsername())
        && StrUtil.isNotBlank(user.getPassword())) {
      this.user = user;
      this.enabled = enabled;
      this.accountNonExpired = accountNonExpired;
      this.credentialsNonExpired = credentialsNonExpired;
      this.accountNonLocked = accountNonLocked;
      if(ObjectUtil.isNotEmpty(resources)){
        this.user.setRoleList(resources.stream()
          .filter(o -> ObjectUtil.isNotEmpty(o.getRoleId()))
          .map(o -> {
          SysRole role = new SysRole();
          role.setId(o.getRoleId());
          role.setName(o.getRoleName());
          return role;
        }).distinct().collect(Collectors.toList()));
        this.authorities = resources.stream()
            .filter(o -> ObjectUtil.isNotEmpty(o.getUrl()))
            .map(UserRoleResourcesDTO::getUrl)
            .distinct()
            .map(o -> new SimpleGrantedAuthority(o))
            .collect(Collectors.toList());
      }
    } else {
      throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
    }
  }

  @Override
  public String getPassword() {
    return user.getPassword();
  }

  @Override
  public String getUsername() {
    return user.getUsername();
  }
}
